package com.lsh.payment.worker.async;

import com.alibaba.fastjson.JSON;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.lsh.base.common.exception.BizCheckedException;
import com.lsh.base.common.utils.BeanMapTransUtils;
import com.lsh.payment.core.model.bill.ThirdPayDetail;
import com.lsh.payment.core.model.payasync.EmailModel;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.model.refund.PayRefund;
import com.lsh.payment.core.service.async.IEventListener;
import com.lsh.payment.core.service.async.PayEventBus;
import com.lsh.payment.core.service.payment.impl.PayDealService;
import com.lsh.payment.core.service.refund.PayRefundOrderService;
import com.lsh.payment.core.util.StringTool;
import com.lsh.payment.worker.kafka.producer.ProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * @author by wuhao
 * Date: 19/10/21
 * 北京链商电子商务有限公司
 * Package com.lsh.payment.worker.async.BillEventListener
 * desc:异步处理监听类
 */
@Component
public class BillEventListener implements IEventListener {
    private Logger logger = LoggerFactory.getLogger(BillEventListener.class);

    @Autowired
    PayRefundOrderService payRefundOrderService;
    @Autowired
    PayDealService payDealService;
    @Autowired
    ProducerService producerService;
    @Value("${to.user.email}")
    private String userEmail;
    /**
     * 对账单校验推送
     *
     * @param thirdPayDetail 监听类
     */
    @Subscribe
    @AllowConcurrentEvents
    public void billCheckAndPush(ThirdPayDetail thirdPayDetail) {
        //校验开始
        // 退款
        try {
            if (thirdPayDetail.getIsRefund().equals("1")) {
                //校验退款金额
                PayRefund payRefund = payRefundOrderService.selectRefundByPayRefundNo(thirdPayDetail.getRefundNo());
                if (payRefund == null) {
                    //有多个系统的单子，这个只关心本系统的
                    return;
                }
                //校验金额
                if (!payRefund.getRefundAmount().equals(thirdPayDetail.getFinalAmount())) {
                    throw new BizCheckedException("11001","退款金额不一致");
                }
                PayDeal payDeal = payDealService.queryPayDealByPayPaymentNo(payRefund.getPayPaymentNo());
                thirdPayDetail.setVenderId(payRefund.getVenderId());
                thirdPayDetail.setTradeType(payDeal.getTradeType());

            } else {
                //支付订单
                PayDeal payDeal = payDealService.queryPayDealByPayPaymentNo(thirdPayDetail.getPayPaymentNo());
                if (payDeal == null) {
                    //只关心本系统的订单
                    return;
                }
                if (!payDeal.getReceiveAmount().equals(thirdPayDetail.getFinalAmount())) {
                    throw new BizCheckedException("11001","支付金额不一致");
                }
                thirdPayDetail.setVenderId(payDeal.getVenderId());
                thirdPayDetail.setTradeType(payDeal.getTradeType());

            }
        }catch (BizCheckedException biz){
            String msg = "";
            if (thirdPayDetail.getIsRefund().equals("1")) {
                msg = "校验对账单异常，对账单类型:退货单,异常对账单号为:" + thirdPayDetail.getRefundNo();
            }else {
                msg = "校验对账单异常，对账单类型:支付订单.异常对账单号为:" + thirdPayDetail.getPayPaymentNo();
            }
            msg = msg + ",异常错误:" + biz.getMessage();
            this.sendMailMsg(msg);
            return;
        }catch (Exception e){
            String msg = "";
            if (thirdPayDetail.getIsRefund().equals("1")) {
                msg = "校验对账单异常，对账单类型:退货单,异常对账单号为:" + thirdPayDetail.getRefundNo();
            }else {
                msg = "校验对账单异常，对账单类型:支付订单.异常对账单号为:" + thirdPayDetail.getPayPaymentNo();
            }
            logger.error(e.getMessage(),e);
            this.sendMailMsg(msg);
            return;
        }


        Map<String,Object>  tmp = BeanMapTransUtils.Bean2map(thirdPayDetail);
        Map<String,Object> kafakResultMap = new HashMap<>();

        for(String key:tmp.keySet()){
            Object val = tmp.get(key);
            key = StringTool.humpToLine2(key);
            kafakResultMap.put(key,val);
        }

        //校验通过，开始推送kafka数据
        producerService.sendJson(JSON.toJSONString(kafakResultMap));
    }
    public void sendMailMsg(String msg){
        logger.info("send email msg :{}",msg);
        String[] userEmails = userEmail.split(",");
        PayEventBus.post(new EmailModel(msg, "对账单校验异常", userEmails));
    }
}
